import GeoLocationField from './SubField/GeoLocationField.js';
import SelectField from './SubField/SelectField.js';
import TextareaField from './SubField/TextareaField.js';
import InputNumber from './SubField/InputNumber.js';

class Field {
  constructor(options) {
    let plusValue = options?.plusValue || "";
    this.uuid = options?.uuid || Date.now().toString() + plusValue;
    //类型，包括input、select、label、geo-input、textarea、image-list-upload
    this.key = options?.key;
    this.type = options?.type || type;
    this.label = options?.label || `${this.type}字段${fieldCounter}`;
    this.placeholder = options?.placeholder || "";
    this.width = options?.width || "200px";
    this.readonly = options?.readonly || false;
    this.required = options?.required || false;
    this.valueFormat = options?.valueFormat || "";
    //dom样式
    this.style = options?.style || "";
    //比如multiple等，用于空间的data-属性
    this.dataAttribute = options?.dataAttribute || {};
    this.options = options?.options || [];
    //option选项来自的Model字段
    this.optionsKey = options?.optionsKey || "";

    if (this.options.length == 0) {
      if (this.type === 'select') {
        this.options = [
          { label: "选项1", value: "1" },
          { label: "选项2", value: "2" }
        ];
      } else if (this.type === 'image-list-upload') {
        this.options = [
          { label: "limit", value: "10" },
          { label: "fileType", value: "png,jpg,jpeg" },
          { label: "fileSize", value: "5" }
        ];
      }
      var fieldItem = this.getFieldItem();
      if (fieldItem) {
        fieldItem.initOptions(this);
      }
    }

  }
  showFieldConfig(formConfig, fieldConfigPanel) {
    // 获取Model字段列表

    let field = this;

    // 生成字段Key下拉框选项

    let html =
      `
        <div class="form-group">
          <label>字段类型</label>
          <input type="text" value="${this.type}" readonly style="background:#f5f5f5;" />
        </div>
      `
    +
     FormConfigManager.getFieldSelect(field.key)
      + `
        <div class="form-group">
          <label>显示标签</label>
          <input type="text" id="fieldLabel" value="${field.label}" />
        </div>
        <div class="form-group">
          <label>占位文本</label>
          <input type="text" id="fieldPlaceholder" value="${field?.placeholder || ''}" />
        </div>
      `;
    if (field.type === 'image-list-upload') {
      html += `
          <div class="form-group">
            <label>上传限制数量</label>
            <input type="number" id="fieldLimit" value="${field.options?.[0]?.value || 10}" min="1" />
          </div>
          <div class="form-group">
            <label>允许的文件类型</label>
            <input type="text" id="fieldFileType" value="${field.options?.[1]?.value || 'png, jpg, jpeg'}" />
          </div>
          <div class="form-group">
            <label>文件大小限制(MB)</label>
            <input type="number" id="fieldFileSize" value="${field.options?.[2]?.value || 5}" min="1" />
          </div>
        `;
    }
    let fielditem = this.getFieldItem();
    if (fielditem) {
      html += fielditem.getOptionsHtml(field);
    }
    if (field.required) {
      html += `
          <div class="form-group">
          <input type="checkbox" id="fieldRequired"  style="width:100px" checked /> 
          <label style="width: 100px; float: inline-start;">必填记录</label>
          </div>
        `;
    } else {
      html += `
          <div class="form-group">
          
          <input type="checkbox" id="fieldRequired" style="width:100px"/> 
          <label style="width: 100px; float: inline-start;">必填记录</label>
          </div>
        `;
    }
    // valueFormat 配置输入框
    html += `
      <div class="form-group">
        <label>值格式化(valueFormat)</label>
        <label class="input-tip" >你可以写function a(){}("参数")</label>
        <textarea type="text" id="fieldValueFormat" placeholder="例：yyyy-MM-dd、#,##0.00" />${field.valueFormat || ''}</textarea>
      </div>
    `;

    html += `
        <div class="form-group">
          <label>自定义样式(style)</label>
          <textarea id="fieldStyle" placeholder="例：color:red; font-weight:bold;" rows="2">${field.style || ''}</textarea>
        </div>
      `;

    fieldConfigPanel.innerHTML = html;

    this.renderFieldOptions(formConfig, fieldConfigPanel);

    this.renderApplyBtn(fieldConfigPanel);
  }
  /**
   * 渲染字段选择器
   * @param {*} formConfig 
   * @returns 
   */
  renderFieldOptions(formConfig, fieldConfigPanel) {
    let field = this;
    if (field.type !== 'select' ) return;

    const modelFields = formConfig.metadata.fields || [];

    let optionsKeyOptions = '<option value="">请选择数据源 Key</option>';
    modelFields.forEach(fieldName => {
      optionsKeyOptions += `<option value="${fieldName}" ${field.optionsKey === fieldName ? 'selected' : ''}>${fieldName}</option>`;
    });
    const optionsKeyInput = `
      <div class="form-group">
        <label>下拉选项</label>
        <select id="fieldOptionsKey">
          ${optionsKeyOptions}
        </select>
      </div>
    `;
    const optionsKeyDiv = document.createElement('div');
    optionsKeyDiv.innerHTML = optionsKeyInput;
    fieldConfigPanel.appendChild(optionsKeyDiv.firstElementChild);

    const optionsItemsInput = `
      <div class="form-group">
        <div id="optionsContainer">
        </div>
      </div>
    `;
    const optionsItemsDiv = document.createElement('div');
    optionsItemsDiv.innerHTML = optionsItemsInput;
    fieldConfigPanel.appendChild(optionsItemsDiv.firstElementChild);
    let optionsContainer = document.getElementById('optionsContainer');

    if (field.options) {
      let optionsDiv = document.createElement('div');
      optionsDiv.id = "optionsDiv";
      optionsContainer.appendChild(optionsDiv);
      field.options.forEach((opt, idx) => {
        const div = document.createElement('div');
        div.className = 'form-group';
        div.innerHTML = `
          <div style="display:flex; gap:5px;">
            <input type="text" value="${opt.label}" placeholder="标签" style="height: 29px;" />
            <input type="text" value="${opt.value}" placeholder="值" style="height: 29px;" />
            <button class="btn" onclick="Field.removeOption(this)" style="width: 100px;">删除</button>
          </div>
        `;
        div.field = field;
        div.formConfig = formConfig;
        optionsDiv.appendChild(div);
      });
    }
    const addBtn = document.createElement('button');
    addBtn.className = 'btn';
    addBtn.textContent = '添加选项';
    addBtn.formConfig = formConfig;
    addBtn.onclick = this.addFieldOption.bind(this);
    optionsContainer.appendChild(addBtn);
  }

  renderApplyBtn(fieldConfigPanel) {
    const applyBtn = document.createElement('div');
    applyBtn.className = 'form-group';
    applyBtn.innerHTML = `
       <button class="btn" onclick="applyFieldConfig()" style="width: 100%; margin-top: 10px;">应用更改</button>
    `;
    fieldConfigPanel.appendChild(applyBtn);
  }

  addFieldOption(sender) {
    const optionsContainer = sender.srcElement.parentElement;
    const div = document.createElement('div');
    div.className = 'form-group';
    div.innerHTML = `
      <div style="display:flex; gap:5px;">
        <input type="text" value="" placeholder="标签" style="height: 29px;" />
        <input type="text" value="" placeholder="值" style="height: 29px;" />
        <button class="btn" onclick="Field.removeOption(this)" style="width: 100px;">删除</button>
      </div>
    `;
    div.field = this;
    div.formConfig = sender.srcElement.formConfig;

    let optionsDiv = optionsContainer.querySelector('#optionsDiv');
    if (!optionsDiv) {
      optionsDiv = document.createElement('div');
      optionsDiv.id = "optionsDiv";
      optionsContainer.appendChild(optionsDiv);
    }
    optionsDiv.appendChild(div);
  }
  // 删除指定索引的选项
  static removeOption(sender) {
    // 从sender的父级元素上取回之前绑定的field和formConfig
    const parentDiv = sender.closest('div.form-group');
    const field = parentDiv.field;
    const formConfig = parentDiv.formConfig;
    if (field.options) {
      let idx = Array.from(parentDiv.parentElement.children).indexOf(parentDiv);

      field.options.splice(idx, 1);
      // 重新渲染选项列表
      sender.parentElement.remove();
    }
  }

  collectSetting() {
    const key = document.getElementById('fieldKey').value;
    const label = document.getElementById('fieldLabel').value;
    const placeholder = document.getElementById('fieldPlaceholder').value;
    const required = document.getElementById('fieldRequired').checked;
    const valueFormat = document.getElementById('fieldValueFormat').value;
    const userStyle = document.getElementById('fieldStyle').value;

    // 更新字段数据
    this.key = key;
    this.label = label;
    this.placeholder = placeholder;
    this.required = required;
    this.valueFormat = valueFormat;
    this.style = userStyle;
  }

  collectOptionSettings() {
    let fieldItem = this.getFieldItem();
    if (fieldItem) {
      fieldItem.collectOptionSettings(this);
    }
  }

  getFieldItem() {
    let fieldItem = null;
    if (this.type === 'geo-location') {
      fieldItem = GeoLocationField;
    }
    else if (this.type === 'select') {
      fieldItem = SelectField;
    }
    else if (this.type === 'textarea') {
      fieldItem = TextareaField;
    }
    else if (this.type === 'input-number') {
      fieldItem = InputNumber;
    }
    return fieldItem;
  }
}
export default Field;